<?php

namespace app\admin\controller;

use think\App;
use think\Config;
use think\Loader;
use think\Request;
use think\Route;

class Plugins
{
    protected $request = null;

    public function __construct(Request $request = null)
    {
        $this->request = $request;
    }

    public function _empty($arguments)
    {
        if($arguments)unset($arguments);
        
        $pathinfo_depr = Config::get('pathinfo_depr');
        list($path) = self::parseUrlPath($this->request->path());

        if($path && empty($path[1]))$path[1] = 'index';

        list($controllerPath, $controllerSub) = strpos($path[1], '.') !== false ? explode('.', $path[1]) : [$path[1], ''];
        if($controllerSub){
            if (!preg_match('/^[A-Za-z](\w)*$/', $controllerPath) || !preg_match('/^[A-Za-z](\w)*$/', $controllerSub)) {
                $controllerSub = '';
            }
        }

        // 取出URL路径式传参值
        $path = $path ? array_slice($path, 3) : [];
        $url = $path ? '/'.implode($pathinfo_depr, $path) : '';

        $controller = Loader::parseName($this->request->controller());        
        $module = explode('.', $controller);
        
        $suffix = App::$suffix || Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '';
        if($controllerSub){
            $controllerName = strtolower($controllerPath) .'\\'. ucfirst($controllerSub).$suffix;
        }else{
            $controllerName = ucfirst(($module[1]??Config::get('default_controller'))).$suffix;
        }

        $class = 'addons\\'.$module[0].'\\admin\\'.Config::get('url_controller_layer').'\\'.$controllerName;

        if (class_exists($class)) {
            $action = strtolower($this->request->action());
            if(method_exists($class, $action)){
                Config::set('template.view_base', '');
                Config::set('template.view_path', ROOT_PATH.'addons'.DS.$module[0].DS.'admin'.DS.'view'.DS);
    
                // 强制使用后台模板布局
                $view = \think\View::instance(Config::get('template'), Config::get('view_replace_str'));
                $view->engine->layout('admin@layout/default');
                
                // 配入传参值
                $url && Route::bindToClass($url, $class, $pathinfo_depr);

                return App::invokeMethod([$class, $action]);
            }
            throw new \think\exception\HttpException(404, 'method not exists:' . $class . '->' . $action . '()');
        }

        throw new \think\exception\HttpException(404, 'class not exists:' . $class);
    }

    /**
     * 解析URL的pathinfo参数和变量
     * @access private
     * @param string $url URL地址
     * @return array
     */
    private static function parseUrlPath($url)
    {
        // 分隔符替换 确保路由定义使用统一的分隔符
        $url = str_replace('|', '/', $url);
        $url = trim($url, '/');
        $var = [];
        if (false !== strpos($url, '?')) {
            // [模块/控制器/操作?]参数1=值1&参数2=值2...
            $info = parse_url($url);
            $path = explode('/', $info['path']);
            parse_str($info['query'], $var);
        } elseif (strpos($url, '/')) {
            // [模块/控制器/操作]
            $path = explode('/', $url);
        } else {
            $path = [$url];
        }
        return [$path, $var];
    }
}